# -*- coding: utf-8 -*-
# 姓名:谚语
# 开发时间:2022/11/12 21:55
from datetime import datetime

from flask import g, current_app
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from comment.modules import db
from comment.modules.account import Account
from comment.modules.deal_record import DealRecord
from comment.modules.invest_record import Invest_record
from comment.modules.expected_return import Expected_return
from comment.utils.gen_trans_id import gen_trans_id
from financial.resources.transaction.const import DealType


class InvestIncomeResource(Resource):
    """某个预期收益到期之后，获取当前的收益"""

    def post(self):
        rp = RequestParser()
        rp.add_argument('return_id')  # 指定预期收益ID
        args = rp.parse_args()
        return_id = int(args.get('return_id'))

        uid = g.user_id
        # 根据登录的用户查询资金账户对象
        account = Account.query.filter(Account.userId == uid).first()
        # 查询当前指定的预期收益对象
        expected_income = Expected_return.query.filter(Expected_return.id == return_id).first()

        if expected_income:
            # 判断当前的收益是否可以 开始获取收益  .date() 得到时间戳(也就是将其转换成长整型)
            cur_date = datetime.now().date()  # 当前系统时间
            expected_date = expected_income.expectedDate.date()  # 收益日期
            if cur_date >= expected_date:  # 如果当前日期 >= 投资到期的日期
                try:
                    # 查询对应的投资记录对象       用户投资记录 == 投资记录id
                    invest = Invest_record.query.filter(Invest_record.pId == expected_income.investRecord).first()
                    invest.pStatus = 2  # 用户投资记录状态  1 表示正式产生收益,2 收益结束 投资结束

                    # 修改用户的资金账户
                    account.interestA += expected_income.expectedMoney  # 修改已赚取利息
                    account.interestTotal -= expected_income.expectedMoney  # 修改总计待收利息
                    account.inverstmentW -= invest.pAmount  # 修改总计待收本金
                    account.frozen -= invest.pAmount  # 修改账户总计冻结总额
                    before_balance = account.balance  # 原帐户可用余额
                    account.balance += (invest.pAmount + expected_income.expectedMoney)  # 修改帐户可用余额
                    account.total += expected_income.expectedMoney  # 修改帐户总金额

                    # 新增一条交易记录
                    # 生成交易流水号
                    del_num = gen_trans_id(DealType.income)
                    # 交易记录的模型类(用户id, 收付,1表示接收,2表示付款, 交易流水号, 交易状态,0代表交易失败,1代表交易成功,
                    #               交易前金额, 产生的交易金额(这里指利息),       交易后金额, 交易详情,      交易类型)
                    deal_log = DealRecord(aUserId=uid, aReceiveOrPay=1, aTransferSerialNo=del_num, aTransferStatus=1,
                                          aBeforeTradingMoney=before_balance, aAmount=expected_income.expectedMoney,
                                          aAfterTradingMoney=account.balance, aDescreption='提取收益',
                                          aType=DealType.income.value)
                    # 将预期收益的可提现金额设置为0
                    expected_income.expectedMoney = 0

                    db.session.add(deal_log)  # 添加至数据库

                    db.session.commit()  # 提交
                    return {'msg': 'success'}
                except Exception as e:
                    current_app.logger.error(e)  # 将错误日志输出出来
                    db.session.rollback()  # 回滚
                    return {'message': '系统出错'}, 500
            else:
                return {'message': '投资未到期', 'code': 20001}
        else:
            return {'message': '没有找到对应的预期收益'}, 401
